<script setup lang="ts">
  import { onMounted, ref, reactive, watch } from 'vue';
  import storage from 'good-storage';
  import { useRouter } from 'vue-router';
  import API_BANNER from '@/apis/banner';
  import { useI18n } from 'vue-i18n';
  import API_HOME from '@/apis/home';
  const props = defineProps(
    {
      show: {
        type: Boolean,
        default: false
      }
    }
  )
  const emit = defineEmits(['closeLan', 'update:show'])

  const { locale } = useI18n()
  let selectedValues = ref([])
  let isMobile = ref(false);
  const localShow = ref(props.show);
  // 监听父组件传入的 show 变化
  watch(() => props.show, (newVal) => {
    localShow.value = newVal;
  });
  onMounted(() => {
    getLangList()
    window.addEventListener('resize', checkDevice);
    checkDevice(); // 初始检测

  });
  // 获取语言列表
  const getLangList = async () => {
    let res = await API_HOME.indexConfigLang();
    if (res.code == 1) {
      columns.value = res.data
      // let defaultItem = res.data.find((i) => {
      //   return i.is_default == 1
      // })
      storage.set('lang', res.data[0].curren_lang
      )

    }
  };
  // 检测设备函数
  const checkDevice = () => {
    isMobile.value = window.innerWidth <= 768;
    if (!isMobile.value) {
      document.addEventListener('click', handleClickOutside);
    }
  };
  // 选择的值
  const openPop = () => {
    let select = storage.get('lang')
    let temp = []
    temp.push(select)
    selectedValues.value = temp
  }
  // 语言切换选择的值
  const columns = ref([
    { text: '中文', value: 'zh-cn' },
    { text: 'English', value: 'en' },
  ]);

  const confirmChange = async () => {


    // 语言赋值
    let res = await API_HOME.indexChangeLang({
      lang: selectedValues.value[0]
    })
    if (res.code == 1) {
      locale.value = selectedValues.value[0]
      storage.set('lang', selectedValues.value[0])
      emit('closeLan', selectedValues.value[0])
      setTimeout(() => {
        window.location.reload();
      }, 300);
    }

  }
  // PC切换语言
  let changePClang = async (e) => {
    // 语言赋值
    let res = await API_HOME.indexChangeLang({
      lang: e.lang
    })
    if (res.code == 1) {
      locale.value = e.lang
      storage.set('lang', e.lang)
      emit('closeLan', e.lang)
      setTimeout(() => {
        window.location.reload();
      }, 300);
    }
  }
  const cancelChange = () => {
    console.log(selectedValues.value[0]);
    emit('closeLan', selectedValues.value[0])
  }
  // 关闭弹出
  const closeIcon = () => {
    emit('closeLan', selectedValues.value[0])
  }
  const closeMask = () => {
    emit('closeLan', selectedValues.value[0])
  }
  let boxRefLang = ref(null);
  // 处理外部点击
  const handleClickOutside = (event) => {
    console.log(event.target.id, '??');
    if (event.target.id === 'lang1') {
      // emit('closeLan')
      return
    }
    // 确保引用存在且不是null
    if (!boxRefLang.value) {
      // 如果菜单元素不存在，移除监听器
      document.removeEventListener('click', handleClickOutside);
      return;
    }
    // 确保点击的不是菜单本身或其子元素
    if (!boxRefLang.value.contains(event.target)) {
      console.log(2);

      emit('closeLan')
    }
  };

</script>

<template>
  <div>
    <div v-if="isMobile">
      <van-popup v-model:show="localShow" round :position="isMobile?'bottom':'top'" @click-close-icon="closeIcon"
        @opened="openPop" @click-overlay="closeMask">
        <van-picker :columns="columns" :columns-field-names="{ text: 'name', value: 'lang'}"
          :confirm-button-text="$t('home.confirm')" :cancel-button-text="$t('home.cancel')" v-model="selectedValues"
          @confirm="confirmChange" @cancel="cancelChange" />
      </van-popup>
    </div>
    <div v-else>
      <div class="animate__animated animate__flipInX downMenu" v-show="localShow" ref="boxRefLang">
        <div class="account_In" v-for="(i,index) in columns" :key="index" @click="changePClang(i)">
          <van-icon name="setting-o" />
          <span>{{i.name}}</span>
        </div>

      </div>
    </div>
  </div>
</template>
<style lang="less" scoped>
  .downMenu {
    border: 1px solid #e5e5e5;
    border-radius: 5px;
    width: 160px;
    position: absolute;
    top: 16px;
    left: -80px;
    z-index: 999;
    background-color: #fff;

    .account {
      color: #888888;
      font-size: 12px;
      border-bottom: 1px solid #e5e5e5;
      padding: 10px;

      .account_log {
        display: flex;
        align-items: center;
      }

      .account_info {
        margin-left: 8px;
        font-size: 12px;

        .name {
          font-weight: 700;
          font-size: 16px;
          color: #000;
        }
      }
    }

    .account_In {
      padding: 10px;
      font-size: 14px;
      display: flex;
      align-items: center;

      span {
        margin-left: 8px;
      }

      &:hover {
        cursor: pointer;
      }
    }
  }
</style>